package com.example.demo;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("header")
public class HeaderController {
    //获取cookie
    @RequestMapping("getCookie")
    public String getCookie(HttpServletRequest request){
        Cookie[] cookies=request.getCookies();
        for(Cookie cookie:cookies){
            System.out.println(cookie.getName()+":"+cookie.getValue());
        }
        return "获取cookie成功";
    }

    @RequestMapping("getCookie2")
    public String getCookie2(@CookieValue("bite") String bite){
        return "从cookie中获取信息:,bite="+bite;
    }
    @RequestMapping("setSession")
    public String setSession(HttpServletRequest request){
        HttpSession session=request.getSession();
        session.setAttribute("name","zhangsan");
        session.setAttribute("age",18);
        return "success设置Session";
    }
    @RequestMapping("getSession")
    public String getSession(HttpServletRequest request){
        HttpSession session= request.getSession();
        if(session.getAttribute("name")==null){
            return "";
        }
       String userName=(String)session.getAttribute("name");
        return "从Session中获取信息：，username="+userName;
    }
    @RequestMapping("getSession2")
    public String getSession2(HttpSession session){
        String username=(String) session.getAttribute("name");
        Integer userage= (Integer) session.getAttribute("age");
        return "username="+username+",userage="+userage;
    }
    @RequestMapping("getHeader")
    public String getHeader(HttpServletRequest request){
        String UA=request.getHeader("User-Agent");
        return "User-Agent="+UA;
    }
    @RequestMapping("getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String UA ){
        return "User-Agent="+UA;
    }
}
